-- UISkyScrapBonus
-- Create by huanghr
-- 荣誉碎片奖励

require "game/ui/misc/UIIndicator"
require "game/ui/form/common/UIBonusNotify"
require "game/ui/form/workshop/UIItemDesc"

--UISkyScrapBonus继承自Layer
UISkyScrapBonus = class("UISkyScrapBonus", function()
    return cc.Layer:create();
end);

function UISkyScrapBonus.create()
    return UISkyScrapBonus.new();
end

-- 构造函数
function UISkyScrapBonus:ctor()
    self:setName("UISkyScrapBonus");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/talent/TalentFruitBonus.csb");
    self:addChild(node);
    self.node = node;

    -- 荣誉碎片的播放动画的缩放大小
    self.honorDebris = {};

    --self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER);
    self:init();

    -- 重绘
    self:redraw();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 适配
    self:resize();
end

-- 重绘
function UISkyScrapBonus:redraw()
    local node = self.node;

    -- 更新奖励气泡
    self:updateBonusBubble();

    -- 设置标题样式
    local titleLabel = findChildByName(node, "CT/title_bg/text");
    titleLabel:setString(getLocStr("world_tree_award"));
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 奖励标题
    local bonusTitleLabel = findChildByName(node, "CT/bonus_title");
    TextStyleM.setTextStyle(bonusTitleLabel, TextStyleM.TEXT_SIZE_MIDDLE2, TextStyleM.TEXT_COLOR_ORANGE, true, -4, nil, nil, nil, nil, true);
    bonusTitleLabel:setString(getLocStr("achive_award"));
    bonusTitleLabel:setPositionY(bonusTitleLabel:getPositionY() - 15);

    -- 奖励需求
    local bonusRequireLabel = findChildByName(node, "CT/bonus_require");
    TextStyleM.setTextStyle(bonusRequireLabel, TextStyleM.TEXT_SIZE_MIDDLE2, TextStyleM.TEXT_COLOR_ORANGE, true, -4, nil, nil, nil, nil, true);
    bonusRequireLabel:setString(getLocStr("sky_honor_piece"));
    bonusRequireLabel:setPositionY(bonusRequireLabel:getPositionY() - 15);
end

-- 注册点击事件
function UISkyScrapBonus:registerTouchEvent()
    -- 注册领取按钮点击事件
    local btnTakeBonus = findChildByName(self.node, "BT/take_bonus");
    local function onTakeBonusClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            local ret = SkyScrapBonusM.takeBonus();
            if ret ~= true then
                if ret == "item_lack" then
                    alert(getLocStr("take_fruit_bonus_fail"));
                elseif ret == "all_taken" then
                    alert(getLocStr("all_taken"));
                end

                -- 播放界面音效
                AudioM.playFx("slime_gain_failed");
                return;
            end

            Operation.cmd_take_sky_scrap_bonus();

            local id = ME.user.dbase:query("sky_scrap_progress", 0);
            self:updateTakenFlag(id);

            self:jumpTo(id);
        end
    end
    btnTakeBonus:addTouchEventListener(onTakeBonusClick);
    TextStyleM.setTextStyle(btnTakeBonus, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnTakeBonus:setTitleText(getLocStr("take_bonus"));

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyScrapBonus");

            -- 检查是否有新的试剂
            ReagentM.checkReagent();
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 注册事件处理回调函数
function UISkyScrapBonus:registerEventCallback()
    -- 关注领取奖励的回调
    EventMgr.register("UISkyScrapBonus", event.TAKE_FRUIT_BONUS, function(args)
        self:whenTakeFruitBonus(args);
        self:updateBonusBubble();
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UISkyScrapBonus", event.FOCUS_CHANGED, function(para)
        -- TODO
        if para["get"] == "UISkyScrapBonus" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_STATUE, TOPMENU_FRAME_HEAD_AIRSHIP);
        elseif para["lose"] == "UISkyScrapBonus" then

        end
    end);

    self:registerScriptHandler(function(ev)
        if ev == "enterTransitionFinish" then
            -- 默认显示最底部内容
            local scrollview = findChildByName(self.node, "CT/scrollview");
            self:jumpTo(self.lastTaken);
        elseif ev == "exit" then
            EventMgr.removeAll("UISkyScrapBonus");
        end
    end);
end

-- 初始化奖励
function UISkyScrapBonus:initItem(node, bonusInfo, id)
    local bonus = bonusInfo[1];

    -- 图标
    local icon = findChildByName(node, "icon");

    local iconPath;
    local name;
    local num = bonus[3];
    local scale = 0.6;
    local offsetY = 0;

    -- 奖励名称
    local nameLabel = findChildByName(node, "name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    -- 需求数量
    local numLabel = findChildByName(node, "num");
    TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    numLabel:setString(tostring(SkyScrapBonusM.query(id, "amount")));
    self.isHonorDebris = false;

    if bonus[1] == 1 then
        -- 是道具， 获取道具图标
        iconPath = getItemIconPath(ItemM.query(bonus[2], "icon"));
        name = ItemM.query(bonus[2], "name");
        scale = 0.6;
        if ItemM.query(bonus[2], "group") == 17 then

            self.isHonorDebris = true;
            scale = 0.5;
        elseif ItemM.query(bonus[2], "group") == 28 then
            -- 配方颜色
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED);
        end
    elseif bonus[1] == 2 then

        name = FieldsM.query(bonus[2], "name");
        scale = 1;
        -- 设置萝卜和钻石颜色
        if "radish" == bonus[2] then
            name = getLocStr("life_limit");
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED);
            iconPath = getLargeAttribIconPath("life");
        elseif "gem" == bonus[2] then
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
            iconPath = getLargeAttribIconPath("gem_large");
        else
            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED);
            iconPath = getLargeAttribIconPath(bonus[2]);
            scale = 0.6;
        end

    elseif bonus[1] == 3 then
        local classId = tonumber(bonus[2]);
        local fileName = PetM.getDefaultIcon(classId);
        iconPath = getHeroIconPath(tostring(fileName));
        name = PetM.query(classId, "name");

        scale = 0.6;
        offsetY = 6 ;
    elseif bonus[1] == 8 then
        local classId = tonumber(bonus[2]);
        local fileName = SkyRobotM.query(classId, "icon");
        iconPath = getRobotIconPath(tostring(fileName));
        name = SkyRobotM.query(classId, "name");

        scale = 0.5;
    end
    icon:loadTexture(iconPath);
    icon:setScale(scale);
    icon:setPositionY(icon:getPositionY()+offsetY);

    if num > 1 then
        nameLabel:setString(string.format("%s×%s", name, num));
    else
        nameLabel:setString(name);
    end

    if bonus[1] == 2 then
       nameLabel:setString(string.format("%s+%s", name, num));
    end

    -- 点击处理
    local bg = findChildByName(node, "touch_bg");
    bg:addTouchEventListener(function(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            showBonusDesc(bonus);
        end
    end);
end

-- 更新是否已领取的标识
function UISkyScrapBonus:updateTakenFlag(id)
    local node = self.itemIcons[id];
    local isTaken = SkyScrapBonusM.isTaken(id);
    if isTaken then
        self.lastTaken = id;
    end

    -- 可领取光效
    local light = findChildByName(node, "light");

    local nameLabel = findChildByName(node, "name");
    local numLabel = findChildByName(node, "num");
    local mengban  = findChildByName(node, "taken_image");
    local itemIcon = findChildByName(node, "icon");

    -- 是否可领取
    local canBeTaken = SkyScrapBonusM.canBeTaken(id);
    if canBeTaken then
        -- 是否已领取

        if isTaken then
            -- 已领取，名字置灰，添加一层黄色蒙版
            mengban:setVisible(true);
            light:setVisible(false);
            itemIcon:stopAllActions();

            TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY);

            TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY);
            if getLang() == "zh" or getLang() == "tw" then
                numLabel:setString(getLocStr("has_received"));
            else
                numLabel:setString("");
            end

        else
            TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN);
            if getLang() == "zh" or getLang() == "tw" then
                numLabel:setString(getLocStr("can_be_taken"));
            end

            light:setVisible(true);
            local rotateForever = cc.RepeatForever:create(cc.RotateBy:create(30, 360));
            light:runAction(rotateForever);

            -- 判断是不是荣誉碎片，荣誉碎片要缩放要小点
            local bonusInfo = SkyScrapBonusM.query(id, "bonus");
            local bonus = bonusInfo[1];
            if self.isHonorDebris then
                playBubbleAnima2(itemIcon, false, 0.5);
            elseif bonus[2] == "radish" then
                playBubbleAnima2(itemIcon, false, 1);
            elseif bonus[2] == "gem" then
                playBubbleAnima2(itemIcon, false, 1);
            else
                playBubbleAnima2(itemIcon, false, 0.6);
            end
        end
    else
        -- 不可领取
        light:setVisible(false);
    end
end

-- 移动中心
function UISkyScrapBonus:jumpTo(id)
    id = iif(id==nil, 1, id);

    id = id - 3;

    local scrollview = findChildByName(self.node, "CT/scrollview");
    local percent = id * 100 / self.totalCount;
    if percent < 0 then
        percent = 0;
    end

    scrollview:jumpToPercentVertical(percent);
end

-- 初始化奖励列表
function UISkyScrapBonus:init()
    local scrollview = findChildByName(self.node, "CT/scrollview");
    scrollview:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/talent/FruitBonusItem.csb");
    local widget = replaceNodeWithWidget(itemNode);

    -- 获取奖励列表
    local bonusList = SkyScrapBonusM.getAllBonusConfig();

    -- 左边距
    local leftMargin = 1;

    -- 行间距
    local gap = 0;
    local widgetHeight = 61;

    local totalNum = 0;
    for k,v in pairs(bonusList) do
        totalNum = totalNum + 1;
    end
    self.totalCount = totalNum;

    local startHeight = 0;

    -- 计算总高度
    local totalHeight = math.max(totalNum * (widgetHeight + gap), scrollview:getInnerContainerSize().height);
    if totalHeight < scrollview:getInnerContainerSize().height then
        startHeight = scrollview:getInnerContainerSize().height - totalHeight;
    end

    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width, totalHeight));

    self.itemIcons = {};
    local i = 0;
    for id, _ in pairs(bonusList) do
        local bonus = SkyScrapBonusM.getFinalBonus(ME.user, id);

        local child = widget:clone();
        local x = leftMargin;
        local y = startHeight + i * (widgetHeight + gap);
        child:setPositionX(x);
        child:setPositionY(y);

        self.itemIcons[id] = child;

        -- 初始化奖励
        child:setTag(i);
        self:initItem(child, bonus, id);
        self:updateTakenFlag(id);

        scrollview:addChild(child);
        i = i + 1;
    end

    UIIndicator.attach(scrollview);
end

-- 适配
function UISkyScrapBonus:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 领取奖励的回调
function UISkyScrapBonus:whenTakeFruitBonus(args)
    local bonusList = args.bonusList;

    if bonusList ~= nil and #bonusList > 0 then
        showBonusNotifyForm(getLocStr("sky_honor_bonus"), bonusList);
    end
end

-- 更新可领取奖励泡泡
function UISkyScrapBonus:updateBonusBubble()
    local hintNode = findChildByName(self.node, "BT/take_bonus/hint");

    -- 如果可领取奖励为0，则领取奖按钮置灰不可用
    local canGetNum = SkyScrapBonusM.getAvailableBonuNum();
    checkBlueBubbleStatus(hintNode, canGetNum);

    if canGetNum < 1 then
        local btnTakeBonus = findChildByName(self.node, "BT/take_bonus");
        btnTakeBonus:setTouchEnabled(false);
        btnTakeBonus:setBright(false);
    end
end
